﻿using Crm.Infrastructure.IOC;
using Crm.Service.EFCore;
using Crm.Service.Instance;
using CRM.Infrastructure.Attr;
using CRM.Infrastructure.Dto.Response;
using CRM.Infrastructure.Dto.Response.Customer;
using CRM.Infrastructure.Dto.Response.Reservation;
using CRM.Infrastructure.EFCore.Mysql;
using CRM.Infrastructure.IOC;
using CRM.Infrastructure.Tools;
using CRM.Service.Interface;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CRM.Service.Instance
{
    [Inject_]
    public class Reservation_Service:Base_Service,I_Reservation_Service
    {
        private readonly Reservation_IOC _reservation_IOC;
        private readonly Customer_IOC _customer_IOC;
        private readonly Order_IOC _order_IOC;
        public Reservation_Service(Reservation_IOC reservation_IOC, Customer_IOC customer_IOC, Order_IOC order_IOC)
        {
            _reservation_IOC = reservation_IOC;
            _customer_IOC = customer_IOC;
            _order_IOC = order_IOC;
        }

        public async Task<Api_Response_Dto> Add_Reservation(Reservation_Response_Dto dto)
        {
            Reservation reservation = new Reservation()
            {
                RId = Config.GUID_2(),
                RCvid = dto.cvid,
                RRid = dto.roomid,
                RStatus = 1,
                RSum = dto.sum,
                RDateTime =Convert.ToDateTime(dto.time),
            };
            _reservation_IOC._reservation_EFCore.Add(reservation);
            _reservation_IOC._reservation_EFCore.SaveChanges();
            var iq = _order_IOC._room_EFCode.QueryAll(d => d.RId == dto.roomid).Single();
            iq.RState = 1;
            iq.RDateTime = Convert.ToDateTime(dto.time);
            _order_IOC._room_EFCode.Update(iq);
            var result = await _order_IOC._room_EFCode.SaveChangesAsync();
            
            
            return Result(result);
        }

        public async Task<Api_Response_Dto> Get_Reservation(int page=1, int limit=10, string? key="")
        {
            var iq = _reservation_IOC._reservation_EFCore.QueryAll(out int total, page, limit,
                false, d => d.RDateTime);
            var data = await iq.Select(d => new Reservation_Response_Dto
            {
                id = d.RId,
                cvid=d.RCvid,
                roomid=d.RRid,
                status=d.RStatus,
                sum=d.RSum,
                time=d.RDateTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
            }).ToListAsync();
            var cv = _customer_IOC._customer_vip_EFCore.QueryAll();
            var room = _order_IOC._room_EFCode.QueryAll();
            data.ForEach(d =>
            {
                d.roomid=room.Where(e=>e.RId==d.roomid).SingleOrDefault()?.RRoom;
            });
            return Result(1, "ok", new
            {
                data,
                total
            });
        }
    }
}
